#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/6 22:48
# @Author  : Andrewq
# @Site    : nope
# @File    : utilResource.py
# @Software: PyCharm
from flask import jsonify, request
import csv
import os
import zipfile

from .departmentResource import DepartmentResource
from .employeeResource import EmployeeResource
from .orderResource import OrderResource
from ..utils.response_code import RET


class UtilResource:

    @classmethod
    def export_data_to_csv(cls):
        datas = eval(request.form.get('data'))

        if not all([datas]):
            return jsonify(code=RET.PARAMERR, msg='缺失参数datas', data=[])

        export_all_data = []

        for data in datas:
            item, statistic = {}, []
            item['title'] = data.get('title')
            if item['title'] == '各部门人员数量统计':
                statistic = eval(DepartmentResource.get_department_person_statistics().data)['data']
            if item['title'] == '人员订阅刊物数量统计':
                statistic = eval(EmployeeResource.get_person_order_statistics().data)['data']
            if item['title'] == '各部门订阅刊物种类统计':
                statistic = eval(DepartmentResource.get_order_department_statistics().data)['data']
            if item['title'] == '订阅各刊物的部门数量统计':
                statistic = eval(OrderResource.get_department_order_statistics().data)['data']
            item['data'] = statistic
            export_all_data.append(item)

        address = './app/static/statistics_csv_files'
        try:

            if not os.path.exists(address):
                os.makedirs(address)

            for export_data in export_all_data:

                file_address = os.path.join(address, "{0}.csv".format(export_data['title']))

                with open(file_address, 'w', encoding='utf-8-sig', newline="") as f:
                    csv_writer = csv.writer(f)
                    if export_data['title'] == '各部门人员数量统计':
                        csv_writer.writerow(['部门', '人数'])
                    elif export_data['title'] == '人员订阅刊物数量统计':
                        csv_writer.writerow(['刊物', '订阅人数'])
                    elif export_data['title'] == '各部门订阅刊物种类统计':
                        csv_writer.writerow(['部门', '刊物种类'])
                    elif export_data['title'] == '订阅各刊物的部门数量统计':
                        csv_writer.writerow(['刊物', '部门数'])
                    for item in export_data['data']:
                        infos = [item['index'], item['number']]
                        csv_writer.writerow(infos)

        except Exception as e:
            print(e)
            return jsonify(code=RET.IOERR, msg='导出{0}异常'.format(export_data['title']))

        try:
            # 需要压缩的文件夹
            input_path = address
            # 压缩后存放位置
            output_path = './app/static'
            # 压缩后的文件名
            output_name = 'statistics_csv_files.zip'
            f = zipfile.ZipFile(output_path + '/' + output_name, 'w', zipfile.ZIP_DEFLATED)
            filelists = []
            files = os.listdir(input_path)
            for file in files:
                if os.path.isdir(input_path + '/' + file):
                    filelists.append(input_path + '/' + filelists)
                else:
                    filelists.append(input_path + '/' + file)

            for file in filelists:
                f.write(file)
            # 调用了close方法才会保证完成压缩
            f.close()
        except Exception as e:
            print(e)
            return jsonify(code=RET.IOERR, msg='生成ZIP文件异常')

        return jsonify(code="200", message="成功！",
                       data={'output_path': './app/static', 'output_name': 'statistics_csv_files.zip'})
